package cn.jiedanba.cacert.mapper.handler;

import java.io.UnsupportedEncodingException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.codec.binary.Base64;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import cn.jiedanba.cacert.common.ca.encryption.SM4Util;
import cn.jiedanba.cacert.common.config.Configs;

/**
 * 私钥加密
 * 
 * @author dell
 *
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
public class CryptoPrivateKeyTypeHandler extends BaseTypeHandler<String> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
			throws SQLException {
		if (parameter != null) {

			// 加密
			String encryptHex = Base64
					.encodeBase64String(SM4Util.encryptEcb(Configs.get("sm4.key"), Base64.decodeBase64(parameter)));
			ps.setString(i, encryptHex);
		}

	}

	@Override
	public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String originRes = rs.getString(columnName);
		if (originRes != null) {

			byte[] res = SM4Util.decryptEcb(Configs.get("sm4.key"), Base64.decodeBase64(originRes));
			return Base64.encodeBase64String(res);
		}
		return null;

	}

	@Override
	public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String originRes = rs.getString(columnIndex);
		if (originRes != null) {
			byte[] res = SM4Util.decryptEcb(Configs.get("sm4.key"), Base64.decodeBase64(originRes));
			return Base64.encodeBase64String(res);
		}
		return null;
	}

	@Override
	public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String originRes = cs.getString(columnIndex);
		if (originRes != null) {
			byte[] res = SM4Util.decryptEcb(Configs.get("sm4.key"), Base64.decodeBase64(originRes));
			try {
				return new String(res, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
